//
//  NetworkTools.swift
//  我的微博
//
//  Created by Creator on 15/10/9.
//  Copyright © 2015年 Creator. All rights reserved.
//

import UIKit
import AFNetworking

 /// 错误的类别标记
private let ZLErrorDomainName = "com.itheima.error.network"

 ///  网络访问错误信息 - 枚举 
private enum ZLnEetworkError: Int {

    case emptyDataError = -1
    case emptyTokenError = -2
    
    ///  错误描述
    private var errorDescrption: String {
        
        switch self {
        case.emptyDataError: return "空数据"
        case.emptyTokenError: return "Token 为空"
        }
    }
    /// 根据枚举类型 返回对应的数据
    private func error() -> NSError {
        return NSError(domain: ZLErrorDomainName, code: rawValue, userInfo: [ZLErrorDomainName: errorDescrption])
    }
}


 ///  网络访问方法
private enum ZLNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    
    private let clientId = "4060354578"
    private let appSecret = "fa9347133364b073644aa289248062e4"
    // 回调地址
    let redirectUri = "http://www.baidu.com"
    
    
    ///  网络回调类型别名
    typealias ZLNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?) ->()
    
    // 单利
    static let sharedTools: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetworkTools(baseURL: baseURL)
        
        // 设置解析数据类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>

        
    return tools
        
    }()
    
    ///   检查并生成字典
    private func tokenDict(finished: ZLNetFinishedCallBack) -> [String: AnyObject]? {
        // 判断 token 是否存在
        if UserAccount.sharedAccount?.access_token == nil {
        
            // 错误回调，token 为空
            let error = ZLnEetworkError.emptyTokenError.error()
            finished(result: nil, error: error)
            
            return nil
        }
        // 生成 token 字典返回
        return ["access_token" : UserAccount.sharedAccount!.access_token!]
    }
    
    
    
    // MARK: - 加载微博数据, 返回微博数据数组
    func loadStatus(since_id: Int, max_id: Int, finished: ZLNetFinishedCallBack) {
        
           // 判断 token是否存在，为 nil 直接返回
            // guard 是 swift 2.0 的新语法 和 if let 刚好相反
            // let 获得的变量，后续可以直接使用，而且一定不为 nil
            guard var params = tokenDict(finished) else {
                
                return
            }
        
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
            // 代码运行至此 一定有值
            let urlString = "2/statuses/home_timeline.json"
            
            request(ZLNetworkMethod.GET, urlString: urlString, params: params, finshed: finished)
        }
    
    
    
    // MARK: - 加载用户数据
    
    ///  加载用户数据
    ///
    ///  - parameter uid:      用户代号字符串
    ///  - parameter finished: 完成回调
    func loadUserInfo(uid: String, finished: ZLNetFinishedCallBack) {
    
        // 判断 token 是否存在

            
            // guard 不仅可以用let，还可以用var
            guard var params = tokenDict(finished) else {
                // params 在此没 nil 一般就直接返回
                return
            }
        
        let urlString = "/2/users/show.json"
        params["uid"] = uid
        // 发送网络请求
        request(ZLNetworkMethod.GET, urlString: urlString, params: params, finshed: finished)
    }
    
    
    // MARK: - OAutn授权
    // 返回OAuth 授权地址
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    ///  加载Token
    func loadAccessToken(code: String, finished: ZLNetFinishedCallBack) {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id" : clientId,
            "client_secret" : appSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirectUri]
        

        request(ZLNetworkMethod.POST, urlString: urlString, params: params, finshed: finished)
        
    }

    // MARK: - 封装 AFN 网络方法， 便于替换网络访问方法, 第三方框架的网络代码全部集中在此
    
    ///  AFN 网路请求   GET / POST
    ///
    ///  - parameter method:    HTTP 方法 GET / POST
    ///  - parameter urlString: URL 完成回调
    ///  - parameter params:    字典参数
    ///  - parameter finshed:   完成回调
    private func request(method: ZLNetworkMethod, urlString: String, params: [String : AnyObject], finshed : ZLNetFinishedCallBack) {
        
        // 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finshed(result: result, error: nil)
            }else {
                // 没有错误，没有结果
                print("没有数据 GET Request \(urlString)")
                
                finshed(result: nil, error: ZLnEetworkError.emptyDataError.error())
            }
            
        }
        // 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            
            print(error)
            finshed(result: nil, error: error)
    }
        
        // 根据 method 来执行的方法
        switch method {
        case.GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case.POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }
    

}
